package net.lahuobao.mall.controller.admin;

import net.lahuobao.mall.entity.admin.MallEtcUserEntity;
import net.lahuobao.mall.entity.admin.MallUserEntity;
import net.lahuobao.mall.exception.CarNoUsedException;
import net.lahuobao.mall.service.admin.MallEtcUserServiceI;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import java.util.List;
import java.util.Set;

/**   
 * @Title: Controller
 * @Description: etc卡用户
 * @author zhangdaihao
 * @date 2017-05-16 11:43:27
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/mallEtcUserController")
public class MallEtcUserController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MallEtcUserController.class);

	@Autowired
	private MallEtcUserServiceI mallEtcUserService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private UserService userService;
	@Autowired
	private Validator validator;
	


	/**
	 * etc卡用户列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/malletcuser/mallEtcUserList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(MallEtcUserEntity mallEtcUser,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(MallEtcUserEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEtcUser, request.getParameterMap());
		this.mallEtcUserService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除etc卡用户
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(MallEtcUserEntity mallEtcUser, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		mallEtcUser = systemService.getEntity(MallEtcUserEntity.class, mallEtcUser.getId());
		message = "etc卡用户删除成功";
		mallEtcUserService.delete(mallEtcUser);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加etc卡用户
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(MallEtcUserEntity mallEtcUser, HttpServletRequest request) {
		String message = null;
		String userName = mallEtcUser.getUserName();
		MallUserEntity user = userService.singleResult("from MallUserEntity where userName='" + userName + "'");
		mallEtcUser.setUserid(user.getId());
		mallEtcUser.setState(1);
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(mallEtcUser.getId())) {
			message = "etc卡用户更新成功";
			MallEtcUserEntity t = mallEtcUserService.get(MallEtcUserEntity.class, mallEtcUser.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(mallEtcUser, t);
				mallEtcUserService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "etc卡用户更新失败";
			}
		} else {
			message = "etc卡用户绑定成功";
			try {
				mallEtcUserService.saveAndUpdateCardRule(mallEtcUser);
			} catch (CarNoUsedException e) {
				//e.printStackTrace();
				j.setSuccess(false);
				message = e.getMessage();
			}
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 查询车牌号是否已申请过etc卡
	 *
	 * @param carNo 车牌号
	 * @return AjaxJson 车牌号是否已申请过etc卡
	 */
	@RequestMapping(params = "isCarNoUsed")
	@ResponseBody
	public AjaxJson isCarNoUsed(String carNo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		boolean isUsed = mallEtcUserService.isCarNoUsed(carNo);
		if (isUsed) {
			j.setSuccess(false);
			j.setMsg("车牌号是否已申请过etc卡");
		}
		return j;
	}

	/**
	 * etc卡用户列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(MallEtcUserEntity mallEtcUser, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(mallEtcUser.getId())) {
			mallEtcUser = mallEtcUserService.getEntity(MallEtcUserEntity.class, mallEtcUser.getId());
			req.setAttribute("mallEtcUserPage", mallEtcUser);
		}
		req.setAttribute("cardno", req.getParameter("cardno"));
		return new ModelAndView("net/lahuobao/mall/admin/mallEtcUser");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<MallEtcUserEntity> list() {
		List<MallEtcUserEntity> listMallEtcUsers=mallEtcUserService.getList(MallEtcUserEntity.class);
		return listMallEtcUsers;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		MallEtcUserEntity task = mallEtcUserService.get(MallEtcUserEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody MallEtcUserEntity mallEtcUser, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallEtcUserEntity>> failures = validator.validate(mallEtcUser);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallEtcUserService.save(mallEtcUser);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		Integer id = mallEtcUser.getId();
		URI uri = uriBuilder.path("/rest/mallEtcUserController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody MallEtcUserEntity mallEtcUser) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallEtcUserEntity>> failures = validator.validate(mallEtcUser);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallEtcUserService.saveOrUpdate(mallEtcUser);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		mallEtcUserService.deleteEntityById(MallEtcUserEntity.class, id);
	}
}
